<template>
  <panel class="w-200px">
    <el-tree ref="treeRef" v-bind="tree" @currentChange="currentChange" :filterNodeMethod="filterNodeMethod"
      :highlight-current="true" :show-checkbox="showCheckBox" @check="check" node-key="id">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          {{ node.label }}
        </span>
      </template>
    </el-tree>
  </panel>
</template>
<script lang="ts" setup>
import { DeptService } from '~/service/sys'

import { onMounted, nextTick } from 'vue'
import { ElTree } from 'element-plus'
import { IDeptTreeData, IDeptTreeNodeItem } from '~/types/sys/IDeptTreeNode'
import elpUtil from '~/utils/elp'
import { ITreeNode } from '~/types/ui/tree/ITreeNode'

export interface DeptTreeProps {
  globalLevel?: boolean
  autoSelectRoot?: boolean
  data?: IDeptTreeData
  currentNode?: IDeptTreeNodeItem
  showCheckBox?: boolean
}

const props = withDefaults(defineProps<DeptTreeProps>(), {
  globalLevel: false,
  autoSelectRoot: true,
  currentNode: null,
  showCheckBox: false
})

const treeRef = elpUtil.tree.createRef()
const tree = elpUtil.tree.defaultProps()

const refresh = () => {
  DeptService.queryTree().then((data) => {
    __setTreeData(data)
  })
}

const __setTreeData = (data: IDeptTreeData) => {
  if (data.length === 1) tree.defaultExpandedKeys = [data[0].id]
  tree.data = data as ITreeNode[]

  emits('update:data', data)
  if (props.currentNode != null) {
    //如果有当前选中节点的情况下刷新，则默认还是选中以前的节点
    //TODO:可能刷新后原来选中的节点不存在了，要重新选中到根节点去
    treeRef.value!.setCurrentKey(props.currentNode[tree.nodeKey])
  } else {
    if (props.autoSelectRoot) {
      nextTick(() => {
        treeRef.value!.setCurrentKey(data[0][tree.nodeKey])
        emitCurrentChange(data[0])
      })
    }
  }
}

const setCheckedKeys = function (keys: string[]) {
  treeRef.value!.setCheckedKeys(keys)
}

defineExpose({
  refresh,
  setCheckedKeys
})

const emits = defineEmits(['check', 'currentChange', 'update:data', 'update:currentNode'])

const currentChange = (node: IDeptTreeNodeItem) => {
  emitCurrentChange(node)
}

const check = (node: IDeptTreeNodeItem, treeObj: object) => {
  emits('check', node, treeObj)
}

const emitCurrentChange = (node) => {
  emits('update:currentNode', node)
  emits('currentChange', node)
}

const filterNodeMethod = (value: string, data: IDeptTreeNodeItem) => {
  if (!value) return true
  return data.text.includes(value)
}

onMounted(() => {
  refresh()
})
</script>
<style scoped lang="scss">
.condition {
  margin-bottom: 4px;
}
</style>
